import os, sys
import win32com.client

win32com.client.gencache.EnsureDispatch ("MAPI.Session")

ATTACHMENTS_FOLDER = "c:/aft/test2"
COUNTER = 1

def process_attachment (attachment):
  global COUNTER
  basename = attachment.Name.encode ("utf-8", "ignore").lower ()
  root, ext = os.path.splitext (basename)
  while True:
    try:
      filepath = os.path.join (ATTACHMENTS_FOLDER, "%d%s" % (COUNTER, ext))
      print "Trying", filepath
      open (filepath, "r")
    except IOError:
      break
    else:
      COUNTER += 1

  try:
    attachment.WriteToFile (filepath)
  except:
    return 0
  else:
    attachments = attachment.Parent
    new_attachment = attachments.Add ()
    new_attachment.Position = 0
    new_attachment.Type = win32com.client.constants.CdoFileLink
    new_attachment.Source = filepath
    new_attachment.Name = attachment.Name
    ## attachment.Delete ()
    return 1

def process_message (message):
  print "Message:", message.Subject
  attachments = message.Attachments
  for n_attachment in range (1, attachments.Count + 1):
    attachment = attachments.Item (n_attachment)
    if attachment.Type == win32com.client.constants.CdoFileData:
      if process_attachment (attachment):
        message.Update ()

if __name__ == '__main__':
  session = win32com.client.gencache.EnsureDispatch ("MAPI.Session")
  session.Logon ()
  messages = session.Inbox.Messages
  message = messages.GetFirst ()
  while message:
    process_message (message)
    message = messages.GetNext ()
